<template>
  <div class="student-manage-container">
    <div class="page-header">
      <h1 class="page-title">学生管理</h1>
      <div class="page-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><plus /></el-icon>添加学生
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="学生姓名" clearable />
        </el-form-item>
        <el-form-item label="学号">
          <el-input v-model="searchForm.studentId" placeholder="学生学号" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 学生列表 -->
    <el-card class="table-card">
      <div class="table-operations">
        <div class="left-operations">
          <el-button
            size="small"
            type="danger"
            :disabled="!multipleSelection.length"
            @click="handleBatchDelete"
          >
            <el-icon><delete /></el-icon>批量删除
          </el-button>
          <el-button
            size="small"
            type="success"
            :disabled="!multipleSelection.length"
            @click="handleBatchExport"
          >
            <el-icon><download /></el-icon>导出选中
          </el-button>
        </div>
        <div class="right-operations">
          <el-button-group>
            <el-button size="small" @click="refreshTable">
              <el-icon><refresh /></el-icon>刷新
            </el-button>
            <el-button size="small">
              <el-icon><setting /></el-icon>列设置
            </el-button>
          </el-button-group>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="studentList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        row-key="id"
        border
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="studentNumber" label="学号" min-width="120" sortable />
        <el-table-column prop="username" label="姓名" min-width="100" />
        <el-table-column prop="phone" label="联系电话" min-width="140" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="role" label="角色" width="80" align="center">
          <template #default="scope">
            <el-tag type="success" size="small">{{ scope.row.role }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160" sortable>
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" link @click="handleView(scope.row)">
              查看
            </el-button>
            <el-button size="small" type="primary" link @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button size="small" type="warning" link @click="handleResetPassword(scope.row)">
              重置密码
            </el-button>
            <el-button size="small" type="danger" link @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 学生详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="650px"
      :before-close="handleDialogClose"
    >
      <el-form
        v-if="dialogType !== 'view'"
        ref="studentFormRef"
        :model="studentForm"
        :rules="studentRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学号" prop="studentNumber">
              <el-input v-model="studentForm.studentNumber" placeholder="请输入学号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="username">
              <el-input v-model="studentForm.username" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="studentForm.gender">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="studentForm.age" :min="16" :max="50" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="studentForm.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="studentForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="studentForm.status">
                <el-radio label="正常">正常</el-radio>
                <el-radio label="禁用">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="studentForm.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 查看模式下的详情展示 -->
      <div v-if="dialogType === 'view'" class="view-container">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学号">{{ studentForm.studentNumber }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ studentForm.username }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ studentForm.phone }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ studentForm.email }}</el-descriptions-item>
          <el-descriptions-item label="角色">
            <span>{{ studentForm.role || '无' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{
            formatDate(studentForm.createdAt as string)
          }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{
            studentForm.remark || '无'
          }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button v-if="dialogType !== 'view'" type="primary" @click="submitForm">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { Plus, Search, Refresh, Delete, Download, Setting } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import {
  getTeacherStudentList,
  updateTeacherStudent,
  deleteTeacherStudent,
  resetTeacherStudentPassword,
} from '@/api/admin'
import type { UserInfo } from '@/api/admin'
import { formatDate } from '@/utils/format'

// 定义Student接口类型
export interface Student extends UserInfo {
  caseCount?: number
  diagnosisCount?: number
  rehabPlanCount?: number
  [key: string]: string | number | undefined // 添加索引签名
}

// 表格相关数据
const loading = ref(false)
const studentList = ref<Student[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const multipleSelection = ref<Student[]>([])

// 搜索表单
interface SearchForm {
  name: string
  studentId: string
  major: string
  grade: string
  [key: string]: string // 添加索引签名
}

const searchForm = reactive<SearchForm>({
  name: '',
  studentId: '',
  major: '',
  grade: '',
})

// 弹窗相关数据
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit' | 'view'>('add') // 'add', 'edit', 'view'
const dialogTitle = computed(() => {
  if (dialogType.value === 'add') return '添加学生'
  if (dialogType.value === 'edit') return '编辑学生'
  return '学生详情'
})

// 学生表单数据
interface StudentForm {
  id: number
  username: string
  email: string
  phone: string
  studentNumber: string
  status: string
  remark: string
  caseCount: number
  diagnosisCount: number
  rehabPlanCount: number
  role: string
  createdAt: string
  [key: string]: string | number
}

const studentFormRef = ref<FormInstance>()
const studentForm = reactive<StudentForm>({
  id: 0,
  username: '',
  email: '',
  phone: '',
  studentNumber: '',
  status: '正常',
  remark: '',
  caseCount: 0,
  diagnosisCount: 0,
  rehabPlanCount: 0,
  role: '',
  createdAt: '',
})

// 表单验证规则
const studentRules = reactive<FormRules>({
  studentNumber: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { pattern: /^\d{8,12}$/, message: '学号格式不正确', trigger: 'blur' },
  ],
  username: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' },
  ],
})

// 获取学生列表数据
const fetchStudents = async () => {
  loading.value = true
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      keyword: searchForm.name || searchForm.studentId || undefined,
    }
    const response = await getTeacherStudentList(params)
    if (response.data) {
      studentList.value = response.data.records as Student[]
      total.value = response.data.total
    }
  } catch (error) {
    ElMessage.error('获取学生列表失败')
    console.error('获取学生列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 选择行变化
const handleSelectionChange = (selection: Student[]) => {
  multipleSelection.value = selection
}

// 页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchStudents()
}

// 每页数量变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchStudents()
}

// 表格操作相关方法
const handleSearch = () => {
  currentPage.value = 1
  fetchStudents()
}

const resetSearch = () => {
  Object.keys(searchForm).forEach((key: string) => {
    searchForm[key] = ''
  })
  handleSearch()
}

const refreshTable = () => {
  fetchStudents()
}

// 弹窗相关方法
const resetForm = () => {
  if (studentFormRef.value) {
    studentFormRef.value.resetFields()
  }
  Object.keys(studentForm).forEach((key: string) => {
    if (key === 'status') {
      studentForm[key] = '正常'
    } else if (['caseCount', 'diagnosisCount', 'rehabPlanCount'].includes(key)) {
      studentForm[key] = 0
    } else {
      studentForm[key] = ''
    }
  })
}

const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

const handleView = (row: Student) => {
  dialogType.value = 'view'
  Object.keys(studentForm).forEach((key: string) => {
    if (key in row) {
      studentForm[key] = row[key] as string | number
    }
  })
  dialogVisible.value = true
}

const handleEdit = (row: Student) => {
  dialogType.value = 'edit'
  Object.keys(studentForm).forEach((key: string) => {
    if (key in row) {
      studentForm[key] = row[key] as string | number
    }
  })
  dialogVisible.value = true
}

const handleDelete = async (row: Student) => {
  try {
    await ElMessageBox.confirm('确认删除该学生信息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await deleteTeacherStudent(row.id)
    ElMessage.success('删除成功')
    fetchStudents()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('删除学生失败:', error)
    }
  }
}

const handleBatchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的学生')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确认删除选中的 ${multipleSelection.value.length} 名学生吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )

    // 批量删除
    await Promise.all(multipleSelection.value.map((student) => deleteTeacherStudent(student.id)))
    ElMessage.success('批量删除成功')
    multipleSelection.value = []
    fetchStudents()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
      console.error('批量删除学生失败:', error)
    }
  }
}

const handleBatchExport = () => {
  ElMessage.success(`已选择 ${multipleSelection.value.length} 条数据，正在导出...`)
  // 这里可以实现真实的导出逻辑
}

const handleResetPassword = async (row: Student) => {
  try {
    await ElMessageBox.confirm('确认重置该学生的密码吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    const newPassword = await resetTeacherStudentPassword(row.id)
    ElMessage.success(`密码重置成功，新密码为: ${newPassword}`)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('重置密码失败')
      console.error('重置密码失败:', error)
    }
  }
}

const handleDialogClose = (done: () => void) => {
  ElMessageBox.confirm('确认关闭？未保存的数据将会丢失', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      done()
    })
    .catch(() => {})
}

const submitForm = async () => {
  if (!studentFormRef.value) return

  try {
    await studentFormRef.value.validate()

    if (dialogType.value === 'edit') {
      await updateTeacherStudent({
        userId: studentForm.id,
        username: studentForm.username,
        phone: studentForm.phone,
        email: studentForm.email,
        role: 'student',
      })
      ElMessage.success('更新成功')
    }

    dialogVisible.value = false
    fetchStudents()
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('操作失败')
  }
}

// 初始化数据
onMounted(() => {
  fetchStudents()
})
</script>

<style scoped>
.student-manage-container {
  padding: 20px;
  box-sizing: border-box;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  color: #303133;
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-card {
  margin-bottom: 20px;
}

.table-operations {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.view-container {
  padding: 10px;
}

.stats-section {
  margin-top: 30px;
}

.stats-section h3 {
  font-size: 18px;
  font-weight: normal;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  background-color: #f8f8f8;
  padding: 15px;
  border-radius: 4px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

/* 确保对话框内的表单元素不被挤压 */
:deep(.el-select),
:deep(.el-date-editor) {
  width: 100%;
}
</style>
